#pragma once

#include<iostream>
#include<string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//公共文件这样的名称
const std::string pipefile = "./fifo";
const mode_t gmode = 0600;
const int gsize = 1024;
const int W = O_WRONLY;
const int R = O_RDONLY;


class fifo
{
private:
    void openfifo(int flag)
    {
        _fd = open(pipefile.c_str(),flag);//打开文件
        if(_fd < 0)
        {
            std::cerr << "打开文件失败" << std::endl;
        }
        std::cout << "打开文件成功" << std::endl;
    }
public:
    fifo():_fd(-1)
    {
        //创建管道
        umask(0);
        int n = ::mkfifo(pipefile.c_str(),gmode);
        if(n < 0)
        {
            std::cerr << "mkfifo" << std::endl;
            return;
        }
        std::cout << "创建文件成功"  << std::endl;
    }
    bool openwait()
    {
        openfifo(R);//打开文件-写
        if(_fd < 0)
        {
            return false;
        }
        return true;
    }
    bool openread()//打开文件-读
    {
        openfifo(W);
        if(_fd < 0)
        {
            return true;
        }
        return false;
    }
    int Wait()
    {
        int code = 0;
        ssize_t n = ::read(_fd,&code,sizeof(code));
        if(n == sizeof(code))
        {
            return 0;
        }
        else if(n == 0)
        {
            return 1;
        }
        else
        {
            return 2;
        }
        return 0;
    }
    void Signal()
    {
        int code = 1;
        ::write(_fd,&code,sizeof(code));
    }

    ~fifo()
    {
        //关闭管道
        if(_fd > 0) ::close(_fd);
        //删除管道
        int n = ::unlink(pipefile.c_str());
        if(n < 0)
        {
            std::cerr << "unlink失败" << std::endl;
            return;
        }
        std::cout << "删除fifo文件成功"  << std::endl;
    }
private:
    int _fd;
};


fifo gpipe;